<?php
/**
 * Created by b17
 * 3/1/12 6:24 PM
 */

namespace Managers\Payment;

class PayPal
{
    private $_paypalParams;

    private $_baseUrl;

    private $_strategy;

    const SESSION_NAME = 'payment';

    public function __construct()
    {
        $this->_paypalParams = \Zend_Registry::get('config')->paypal;
        $this->_baseUrl = \Zend_Registry::get('config')->resources->frontController->baseUrl;
        $this->_strategy = new \Managers\Payment\Strategy\MoneyExpressStrategy();
    }

    /**
     * Выволняет начальный запрос для Express Checkout.
     * @throws \Exception
     * @param $moneyCount
     * @return void
     */
    public function setExpressPayment($moneyCount)
    {
        $adapter = new \G4T\Payment\PayPal($this->_paypalParams->uri);
        $adapter->setExpressStrategy($this->_strategy);

        $baseUrl = \Zend_Registry::get('config')->resources->frontController->baseUrl;
        $returnUrl = $baseUrl . 'payment/complete';
        $canceledUrl = $baseUrl . 'payment/cancelled';

        $reply = $adapter->ecSetExpressCheckout($returnUrl, $canceledUrl, $moneyCount);

        if (!$reply->isSuccessful()) {
            throw new \LogicException('Cannot connect you PayPal service. Please, try again later.');
        }

        $replyData = $adapter->parse($reply->getBody());
        if (!preg_match('/success/i', $replyData['ACK'])) {
            throw new \LogicException('Response from PayPal is not success.');
        }

        $session = new \Zend_Session_Namespace(self::SESSION_NAME);
        $session->moneyCount = $moneyCount;
        $amount = $this->_paypalParams->price * $moneyCount;
        $session->amount = $amount;

        $token = $replyData['TOKEN'];
        header('Location: ' .
            $adapter->api_expresscheckout_uri .
            '?&cmd=_express-checkout&token=' . $token);
        die;
    }

    /**
     * Выполняет платежный запрос ExpressCheckout.
     * @throws \Exception
     * @param $userId
     * @param $params
     * @return void
     */
    public function doExpressPayment($userId, $params)
    {
        $token = $params['token'];
        $payer_id = $params['PayerID'];

        $session = new \Zend_Session_Namespace(self::SESSION_NAME);
        $amount = $session->amount;

        $adapter = new \G4T\Payment\PayPal($this->_paypalParams->uri);
        $reply = $adapter->ecDoExpressCheckout($token, $payer_id, $amount);

        if (!$reply->isSuccessful()) {
            throw new \LogicException('Cannot connect you PayPal service. Please, try again later.');
        }

        $replyData = $adapter->parse($reply->getBody());

        if (!preg_match('/success/i', $replyData['ACK']) || !preg_match('/completed/i', $replyData['PAYMENTSTATUS'])) {
            throw new \LogicException('Payment status is not completed.');
        }

        $moneyCount = $session->moneyCount;
        $usersManager = new \Managers\Users();
        $user = $usersManager->increaseMoney($userId, $moneyCount);

        $transactionsManager = new \Managers\Transaction();
        $order = $transactionsManager->create($user, $moneyCount, $replyData['TRANSACTIONID']);

        $session->amount = 0;
    }

    /**
     * Выполняет прямой платеж.
     * @throws \Exception
     * @param $userId
     * @param $params
     * @return
     */
    public function doDirectPayment($userId, $params) {

        $adapter = new \G4T\Payment\PayPal($this->_paypalParams->uri);
        $moneyCount = intval($params['money']);

        $amount = $moneyCount * $this->_paypalParams->price;

        if($amount == 0) {
            throw new \LogicException('No items to buy.');
        }

        $reply = $adapter->doDirectPayment($amount, $params, '127.0.0.1');
        $replyData = $adapter->parse($reply->getBody());

        if (!preg_match('/success/i', $replyData['ACK'])) {
            throw new \LogicException('Payment status is not success.');
        }

        $usersManager = new \Managers\Users();
        $user = $usersManager->increaseMoney($userId, $moneyCount);

        $transactionsManager = new \Managers\Transaction();
        $order = $transactionsManager->create($user, $moneyCount,$replyData['TRANSACTIONID']);
        return $order;

    }
}
